
import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import '../entity/book_entity.dart';
import '../event/inventory_event.dart';
import '../http/api.dart';
import '../main.dart';
import '../serial/send_helper.dart';
import '../util/analysis_book_rule.dart';
import '../util/toast_util.dart';

class Query extends StatefulWidget {
  const Query({Key? key}) : super(key: key);

  @override
  State<Query> createState() => _QueryState();
}

class _QueryState extends State<Query> {

  RxList<BookEntity> bookList = RxList();
  var _keyword = '';
  var page = 1;
  var limit = 10;

  RxString posNo = RxString('');

  final ScrollController _scrollController = ScrollController();
  StreamSubscription? subscription;


  @override
  initState() {
    super.initState();
    _scrollController.addListener(() {
      if (_scrollController.position.pixels ==
          _scrollController.position.maxScrollExtent) {
        page++;
        _loadMore();
      }
    });

    subscription = eventFactory.on<InventoryEvent>().listen((event) {
      print('epc = ${event.data}');
      var no = analysisBookNoRule(event.data);
      if(no == null || no.isEmpty){
        return;
      }
      print('no = ${no}');
      print('posNo = ${posNo.value}');
      if(posNo.value == no){
        di.play('audio/di.wav');
      }

    });

    // uhfSerialPortHelper.sendData(start());

    player.play('audio/keyword.mp3');
  }

  _loadMore() async {
    var list = await query(_keyword, page, limit);
    if(list != null){
      if(page == 1){
        bookList.clear();
      }
      bookList.addAll(list);
    }else{
      if(page == 1){
        bookList.clear();
      }
    }
  }

  @override
  void dispose() {
    _scrollController.dispose();
    subscription?.cancel();
    subscription = null;
    super.dispose();
  }

  _title(){
    return Container(
        margin: EdgeInsets.only(top: 12.h,bottom: 10.h),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            Image.asset("assets/images/down_title.png",width: 60.w,fit: BoxFit.fitWidth,),

            InkWell(
              onTap: (){
                // uhfSerialPortHelper.sendData(stop());
                Get.back();
              },
              child: Image.asset("assets/images/index.png",width: 60.w,fit: BoxFit.fitWidth,)
            )
          ],
        )
    );
  }


  _searchBarWidget(){
    return Row(
      children: [
        Container(
            width: 300.w,
            decoration:BoxDecoration(
              color: Colors.white,
              border: Border.all(color: Colors.grey, width: 0.5.w), // 设置边框颜色和宽度
              borderRadius: BorderRadius.all(Radius.circular(4.r)),
            ),
            padding: EdgeInsets.only(left:10.r),
            margin: EdgeInsets.only(bottom: 10.r),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                const Icon(Icons.search,color: Colors.black,),
                SizedBox(
                  width: 220.w,
                  child: TextField(
                    minLines: 1,
                    textInputAction: TextInputAction.search,
                    onChanged: (input){
                      _keyword = input;
                    },
                    decoration: InputDecoration(
                        contentPadding: EdgeInsets.only(top: 8.r,bottom: 8.r),
                        isCollapsed: true,
                        hintText: "可根据 条码号、书名、索书号搜索",
                        border: InputBorder.none,
                        hintStyle: TextStyle(color: Colors.black,fontSize: 8.sp)
                    ),
                    style: TextStyle(color: Colors.black,fontSize: 8.sp),
                  ),

                ),
                InkWell(
                  onTap: (){
                    if(_keyword.isEmpty){
                      toastWarn('内容不能为空');
                      return;
                    }
                    page = 1;
                    _loadMore();
                  },
                  child: Container(
                      width: 60.w,
                      height: 26.h,
                      decoration:BoxDecoration(
                        color: Colors.blue,
                        borderRadius: BorderRadius.only(topRight:Radius.circular(4.r),bottomRight: Radius.circular(4.r)),
                      ),
                      alignment: Alignment.center,
                      child: Text('查找',style: TextStyle(color: Colors.white,fontSize: 8.sp),)
                  ),
                )
              ],
            )
        ),
        const SizedBox(),
      ],
    );
  }


  _label(){
    return Row(
      children: [
        _labelText('序号',60.w),
        _labelText('条码号',80.w),
        _labelText('书名',180.w),
        _labelText('索书号',80.w),
        _labelText('馆藏状态',40.w),
        _labelText('存放位置',100.w),
        _labelText('定位',60.w),
      ],
    );
  }

  _labelText(text,width){
    return Container(
      width: width,
      height: 24.h,
      alignment: Alignment.center,
      decoration: const BoxDecoration(
        color: Color.fromRGBO(241, 245, 255, 1),
      ),
      child: Text(text,style: TextStyle(color: Colors.black,fontSize: 8.sp),),
    );
  }

  _valueText(text,width,{Color color = Colors.black}){
    return Container(
      width: width,
      height: 24.h,
      alignment: Alignment.center,
      decoration: const BoxDecoration(
        color: Colors.white
      ),
      child: Text(text,style: TextStyle(color: color,fontSize: 8.sp),),
    );
  }

  _list(){
    return Obx(() => SizedBox(
      height: 220.h,
      child: ListView.separated(
        itemBuilder: (context, index) {
          return _listItem(index);
        },
        itemCount: bookList.length,
        separatorBuilder: (BuildContext context, int index) {
          return const Divider(height: 0.5);
        },
      )
    ));
  }

  _listItem(index){
    var item = bookList[index];
    return Row(
      children: [
        _valueText('${index+1}',60.w),
        _valueText('${item.no}',80.w),
        _valueText('${item.mainTitle}',180.w),
        _valueText('${item.searchNo}',80.w),
        _valueText('${item.stateValue?.replaceAll('in', '在馆').replaceAll('borrowed', '借出')}',40.w),
        _valueText('${item.placeName}',100.w),
         InkWell(
           onTap: (){
             if(posNo.value != item.no!){
               posNo.value = item.no!;
             }
           },
           child: SizedBox(
             width: 60.w,
             child:  Row(
               mainAxisAlignment: MainAxisAlignment.center,
               children: [
                 const Icon(Icons.gps_fixed,color: Colors.blue,),
                 Obx(() => Text(posNo.value == item.no?'定位中..':'定位',style: TextStyle(fontSize: 8.sp,color: Colors.blue),))
               ],
             ),
           ),
         )
      ],
    );
  }


  _container(){
    return Container(
      width: 620.w,
      height: 310.h,
      padding: EdgeInsets.all(10.w),
      decoration:  BoxDecoration(
        borderRadius: BorderRadius.all(Radius.circular(4.r)),
        color: Colors.white
      ),
      child: Column(
        children: [
          _searchBarWidget(),
          _label(),
          Obx(() => bookList.isEmpty?
            Container(
              width: double.infinity,
              height: 140.h,
              alignment: Alignment.center,
              child:
                Column(children: [
                  SizedBox(height: 40.h,),
                  Image.asset("assets/images/empty.png",width: 160.w,fit: BoxFit.fitWidth,)
                ],
              ),
            ) :_list()
          ),
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      resizeToAvoidBottomInset: false,
      body: Container(
        width: double.infinity,
        height: double.infinity,
        padding: EdgeInsets.only(left: 10.w,right: 10.w),
        decoration: const BoxDecoration(
          image: DecorationImage(
            fit: BoxFit.fill,
            image: AssetImage(
              "assets/images/bg.png",
            ),
          ),
        ),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            _title(),
            _container(),
          ],
        )
      ),
    );
  }
}